package com.ljs.springbootinit.bizMq;

import com.ljs.springbootinit.common.ErrorCode;
import com.ljs.springbootinit.constant.CommonConstant;
import com.ljs.springbootinit.exception.BusinessException;
import com.ljs.springbootinit.manager.AiManage;
import com.ljs.springbootinit.model.entity.Chart;
import com.ljs.springbootinit.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class BiMessageConsumer {
    @Resource
    private ChartService chartService;
    @Resource
    private AiManage aiManage;

    @SneakyThrows
    @RabbitListener(queues = {BiConstant.BI_QueueName}, ackMode = "MANUAL")
    public void receiveMessage(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliverTag, String message) {
        log.info("receiveMessage={}", message);

        if (StringUtils.isBlank(message)) {
            channel.basicNack(deliverTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }

        Long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);

        if (chart==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"图片为空");
        }

        //先将图标任务状态设置’执行中‘，等执行完后在修改为”完成“，保存执行结果”，若为失败，则执行完修改为”失败”，记录失败信息
        Chart updateChat = new Chart();
        updateChat.setId(chart.getId());
        updateChat.setStatus("running");
        boolean b = chartService.updateById(updateChat);
        if (!b) {
            handleChartUpdateError(chart.getId(), "更新状态执行中失败");
        }

        //调用Ai生成
        String answer = aiManage.doChat(CommonConstant.MODEL_ID, buildUserInput(chart));
        String[] splits = answer.split("【【【【【");
        if (splits.length < 3) {
            handleChartUpdateError(chart.getId(), "更新状态执行中失败");
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        Chart updateChartResult = new Chart();
        //todo 定义枚举

        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        updateChartResult.setStatus("succeed");
        boolean result = chartService.updateById(updateChartResult);
       if (!result) {
            handleChartUpdateError(chart.getId(), "更新成功状态失败");
        }

    }

    /**
     * 构建用户输入
     * @param chart
     * @return
     */
    private String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();

        //构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求").append("\n");
        String userGOal = goal;
        if (StringUtils.isNotBlank(userGOal)) {
            userGOal += goal + "," + chartType;
        }

        userInput.append(userGOal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append("数据：").append(csvData).append("\n");
        return userInput.toString();
    }

    private void handleChartUpdateError(Long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("Failed");
        updateChartResult.setExecMessage(execMessage);
        boolean b = chartService.updateById(updateChartResult);
        if (!b) {
            log.error("更新图标状态失败失败" + chartId + "," + execMessage);
        }
    }

}

